// components/customSticky/customSticky.js
Component({
  options: {
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    scrollTop: {
      type: Number,
      value: 0, 
      observer:function(newVal,oldVal,change){
        console.log(newVal, oldVal, change)
        this.newScrollTop = newVal
        // console.log(this.newScrollTop)
        //方法
        this.updateStickyChange()
      }
    },
    stickyHeight: { 
      type: String,
      value: 'auto'
    },//暂时没用
    stickyTop: {
      type: Number,
      default: 0
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    newScrollTop: 0,
    timer: null,
    top: 0,
    isFixed: false,
  },
  // observers: {
  //   'scrollTop': function (space) {
  //     this.newScrollTop = space
  //     console.log(this.newScrollTop)
  //     //方法
  //     this.updateStickyChange()
  //   }
  // },

  lifetimes: {
    //在组件实例刚刚被创建时执行
    created() {

      
    },
    //在组件实例进入页面节点树时执行
    attached() { 
      // console.log("在组件实例进入页面节点树时执行")
      this.updateScrollChange()
    },
    //在组件在视图层布局完成后执行
    ready() {
      console.log("在组件在视图层布局完成后执行")
      this.updateScrollChange()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取位置
    updateScrollChange() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
      this.timer = setTimeout(() => {
        const className = '.customStickyView';
        const query = wx.createSelectorQuery().in(this)
        query.select(className).boundingClientRect((res) => {
          if (res) {
            this.top = res.top + (this.scrollTop || 0);
          }
        }).exec()
      }, 0)
    },
    //获取顶部间隔
    updateStickyChange() {
      const tempTop = this.top;
      const tempScrollToTop = this.newScrollTop
      let stickyTop = this.properties.stickyTop
      //判断是否悬浮
      let boolType = (tempScrollToTop + stickyTop >= tempTop) ? true : false
      console.log(boolType)
      if (this.isFixed != boolType) {
        // console.log("状态切换了s")
        this.isFixed = boolType
        this.setData({
          isFixed:this.isFixed
        })
      } 
      
    },
  }
})
